package com.jzr.bedside.ui

import android.content.Intent
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.utils.LogUtils
import com.blankj.utilcode.utils.StringUtils
import com.blankj.utilcode.utils.ToastUtils
import com.google.gson.Gson
import com.jzr.bedside.R
import com.jzr.bedside.base.BaseActivity
import com.jzr.bedside.base.BaseApplication
import com.jzr.bedside.base.BaseApplication.Companion.MAIN_EXECUTOR
import com.jzr.bedside.base.BaseEvenBus
import com.jzr.bedside.bean.BedInfoBean
import com.jzr.bedside.bean.TemperatureBean
import com.jzr.bedside.bean.body.CallBody
import com.jzr.bedside.presenter.contract.MainActivityContract
import com.jzr.bedside.presenter.impl.MainActivityImpl
import com.jzr.bedside.service.KeepLiveService
import com.jzr.bedside.ui.adapter.CareLabelAdapter
import com.jzr.bedside.ui.voip.VoipActivity
import com.jzr.bedside.ui.voip.VoipAudioActivity
import com.jzr.bedside.utils.AreaClickListener
import com.jzr.bedside.utils.CommonUtil
import com.jzr.bedside.utils.PreferUtil
import com.jzr.bedside.view.CustomDialog
import com.jzr.netty.common.base.BaseMsg
import com.jzr.netty.common.base.MsgType
import kotlinx.android.synthetic.main.actionbar_root_layout.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.include_main_left.*
import okhttp3.MediaType
import okhttp3.RequestBody
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit

class MainActivity : BaseActivity(), View.OnClickListener, MainActivityContract.View {


    private val mPrensenter = MainActivityImpl()
    private var adapter: CareLabelAdapter? = null
    private var careLabelListBean = mutableListOf<BedInfoBean.DataBean.CareLabelListBean>()

    private var data: BedInfoBean? = null

    private var task: ScheduledFuture<*>? = null

    private var dialogPass: CustomDialog? = null


    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun attachView() {
        mPrensenter.attachView(this)
    }

    override fun detachView() {
        mPrensenter.detachView()
    }

    override fun onRestart() {
        super.onRestart()

        mPrensenter.getBedInfo(
            "bedCode", PreferUtil.getInstance().bedCode,
            "deptCode", PreferUtil.getInstance().deptCode
        )
    }

    override fun initView() {

        setSwipeBackEnable(false)

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        ivRight.setOnClickListener(this)
        btnVideo.setOnClickListener(this)
        btnVoice.setOnClickListener(this)
        rlMoom.setOnClickListener(this)
        rlRest.setOnClickListener(this)
        rlLook.setOnClickListener(this)

        settingsArea.setOnClickListener(AreaClickListener(5, 500, AreaClickListener.ClickEvent {
            startActivityIn(
                Intent(this@MainActivity, SettingActivity::class.java),
                this@MainActivity
            )
        }))

        MAIN_EXECUTOR.scheduleWithFixedDelay({
            mPrensenter.getBedInfo(
                "bedCode", PreferUtil.getInstance().bedCode,
                "deptCode", PreferUtil.getInstance().deptCode
            )
        }, 0, 1, TimeUnit.HOURS)

        adapter = CareLabelAdapter(careLabelListBean)
        rvDoctorOrder.adapter = adapter
        val manage = LinearLayoutManager(this)
        manage.orientation = LinearLayoutManager.VERTICAL
        rvDoctorOrder.layoutManager = manage
        startService()

    }

    @Subscribe
    fun getEventBus(baseMsg: BaseEvenBus) {
        when (baseMsg.messageId) {
            BaseEvenBus.RELOAD -> {
                mPrensenter.getBedInfo(
                    "bedCode", PreferUtil.getInstance().bedCode,
                    "deptCode", PreferUtil.getInstance().deptCode
                )
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private fun startService() {
        val intent = Intent(this@MainActivity, KeepLiveService::class.java)
        startService(intent)
    }

    private  fun showPassDialog(){

        hidePassDialog()
        val view = View.inflate(BaseApplication.getContext(), R.layout.dialog_pass, null)

        val ivDelete = view.findViewById<ImageView>(R.id.ivDelete)
        val btnCalcen = view.findViewById<Button>(R.id.btnCalcen)
        val btnPost = view.findViewById<Button>(R.id.btnPost)
        val edPass = view.findViewById<EditText>(R.id.edPass)

        ivDelete.setOnClickListener {
            hidePassDialog()
        }

        btnCalcen.setOnClickListener {
            hidePassDialog()
        }

        btnPost.setOnClickListener {

            val strPass = edPass.text.toString()
            if(!StringUtils.isEmpty(strPass) && strPass == PreferUtil.getInstance().pass ){
                hidePassDialog()
                tvDiagnose.visibility = View.VISIBLE
                rlLook.visibility = View.GONE
                task = BaseApplication.MAIN_EXECUTOR.schedule({
                    runOnUiThread {
                        tvDiagnose.visibility = View.GONE
                        rlLook.visibility = View.VISIBLE
                        task?.cancel(false)
                        task = null
                    }
                }, 10, TimeUnit.SECONDS)
            }else{
                ToastUtils.showShortToast("密码错误")
            }
        }

        dialogPass = CustomDialog(this, view, R.style.MyDialog)
        dialogPass?.setCancelable(true)
        dialogPass?.show()

    }

    private  fun hidePassDialog(){
        if (dialogPass != null && dialogPass?.isShowing!!) {
            dialogPass?.dismiss()
            dialogPass = null
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.rlLook -> {
                showPassDialog()
            }

            R.id.ivRight -> {
                val i = Intent(this, SkillMainActivity::class.java)
                startActivityIn(i, this)
            }

            R.id.btnVideo -> {
//                val intent = Intent(this, VoipActivity::class.java)
//                intent.putExtra("targetId", PreferUtil.getInstance().deptCode)
//                intent.putExtra("ACTION", "CALLING")
//                startActivityIn(intent, this)

                val body = CallBody()
                body.bedNo=   this.data?.data?.bedCode
                body.cureNo = this.data?.data?.cureNo
                body.deptCode = PreferUtil.getInstance().deptCode
                body.name = this.data?.data?.name

                val dto: RequestBody =
                    RequestBody.create(
                        MediaType.parse("application/json; charset=utf-8"),
                        Gson().toJson(body)
                    )
                mPrensenter.getCall(this,dto)

            }

            R.id.btnVoice -> {
//                val intent = Intent(this, VoipAudioActivity::class.java)
//                intent.putExtra("targetId", PreferUtil.getInstance().deptCode)
//                intent.putExtra(VoipAudioActivity.ACTION, VoipAudioActivity.CALLING)
//                startActivity(intent)
                val body = CallBody()
                body.bedNo=   this.data?.data?.bedCode
                body.cureNo = this.data?.data?.cureNo
                body.deptCode =  PreferUtil.getInstance().deptCode
                body.name = this.data?.data?.name

                val dto: RequestBody =
                    RequestBody.create(
                        MediaType.parse("application/json; charset=utf-8"),
                        Gson().toJson(body)
                    )
                mPrensenter.getCall(this,dto)
            }

            R.id.rlMoom -> {
                val intent = Intent(this@MainActivity, LockScreenMactivity::class.java)
                intent.putExtra("data", Gson().toJson(this.data))
                startActivityIn(intent, this@MainActivity)
//                this.finish()
            }
            R.id.rlRest -> {
                mPrensenter.getBedInfo(
                    "bedCode", PreferUtil.getInstance().bedCode,
                    "deptCode", PreferUtil.getInstance().deptCode
                )

            }

        }
    }

    override fun getBedInfoSuccess(data: BedInfoBean?) {
        if(data?.data!=null){

            this.data = data
            tvName.text = data.data?.name
            tvSex.text = data.data?.sexText
            tvAge.text = data.data?.age
            tvBedNum.text = data.data?.bedCode
            tvDutydoctor.text = data.data?.doctorName
            tvCureno.text = data.data?.cureNo
            tvJoinTime.text = data.data?.inwardTime
            tvDutyNurse.text = data.data?.nurseName
            tvNurseLevel.text = data.data?.nurseLevelName
            tvNurse.text = data.data?.nurseName2
            tvDiagnose.text = data.data?.diagnose?.replace("\n", "")?.replace("\r", "");

            data.data?.patientId.let {
                PreferUtil.getInstance().patientId = it.toString()
            }

            data.data?.cureNo.let {
                PreferUtil.getInstance().cureNo = it
            }

            data.data?.name.let {
                PreferUtil.getInstance().name = it
            }

            adapter?.setNewData(data.data?.careLabelList)
            adapter?.notifyDataSetChanged()
        }else{
            this.data = null
            tvName.text = "暂无病人"
            tvBedNum.text =PreferUtil.getInstance().bedCode
            tvSex.text =""
            tvAge.text  =""
            tvDutydoctor.text =""
            tvCureno.text =""
            tvJoinTime.text =""
            tvDutyNurse.text =""
            tvNurseLevel.text =""
            tvNurse.text =""
            tvDiagnose.text =""
            PreferUtil.getInstance().patientId =""
            PreferUtil.getInstance().cureNo =""
            adapter?.setNewData(null)
            adapter?.notifyDataSetChanged()
        }


    }

    /**
     * 呼叫成功
     */
    override fun getCallSuccess(data: TemperatureBean) {

    }

    override fun showError(message: String?) {
        ToastUtils.showShortToast(message)
    }

}
